/**
 * 配送管理服务
 * 基于LeanCloud进行配送数据的CRUD操作
 */

import { dataAPI } from '@/http/leancloud';

export interface DeliveryData {
  objectId?: string;
  orderId?: any;
  cargoNo: string;
  orderNo: string;
  receiverName: string;
  receiverPhone: string;
  receiverAddress: string;
  senderName: string;
  senderPhone: string;
  senderAddress: string;
  cargoType: string;
  totalQuantity: number;
  totalVolume: number;
  totalWeight: number;
  paymentMethod: number;
  declaredValue: number;
  insuranceFee: number;
  deliveryFee: number;
  unloadingFee: number;
  collectOnDelivery: number; // 代收货款
  status: number; // 0待签收 1已签收 2已拒签 3异常
  signTime?: Date;
  rejectTime?: Date;
  rejectReason?: string;
  deliveryTime?: Date;
  driverId?: string;
  driverName?: string;
  driverPhone?: string;
  vehiclePlate?: string;
}

export interface DeliveryQueryParams {
  cargoNo?: string;
  orderNo?: string;
  senderInfo?: string;
  receiverInfo?: string;
  status?: number;
  paymentMethod?: number;
  startDate?: string;
  endDate?: string;
  page?: number;
  pageSize?: number;
}

/**
 * 配送服务类
 */
export class DeliveryService {
  private static readonly CLASS_NAME = 'Delivery';

  /**
   * 查询配送列表
   */
  static async getDeliveryList(params: DeliveryQueryParams = {}) {
    try {
      const query: any = {};
      
      // 构建查询条件
      if (params.cargoNo) {
        query.cargoNo = { $regex: params.cargoNo };
      }
      if (params.orderNo) {
        query.orderNo = { $regex: params.orderNo };
      }
      if (params.senderInfo) {
        query.$or = [
          { senderName: { $regex: params.senderInfo } },
          { senderPhone: { $regex: params.senderInfo } },
          { senderAddress: { $regex: params.senderInfo } }
        ];
      }
      if (params.receiverInfo) {
        query.$or = [
          { receiverName: { $regex: params.receiverInfo } },
          { receiverPhone: { $regex: params.receiverInfo } },
          { receiverAddress: { $regex: params.receiverInfo } }
        ];
      }
      if (params.status !== undefined) {
        query.status = params.status;
      }
      if (params.paymentMethod !== undefined) {
        query.paymentMethod = params.paymentMethod;
      }
      if (params.startDate && params.endDate) {
        query.deliveryTime = {
          $gte: new Date(params.startDate),
          $lte: new Date(params.endDate)
        };
      }

      const data = await dataAPI.query(this.CLASS_NAME, query);
      return {
        success: true,
        data: data.map(this.formatDeliveryData),
        total: data.length
      };
    } catch (error) {
      console.error('查询配送列表失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 获取待签收配送
   */
  static async getPendingDeliveries(params: DeliveryQueryParams = {}) {
    return await this.getDeliveryList({ ...params, status: 0 });
  }

  /**
   * 获取已签收配送
   */
  static async getSignedDeliveries(params: DeliveryQueryParams = {}) {
    return await this.getDeliveryList({ ...params, status: 1 });
  }

  /**
   * 获取已拒签配送
   */
  static async getRejectedDeliveries(params: DeliveryQueryParams = {}) {
    return await this.getDeliveryList({ ...params, status: 2 });
  }

  /**
   * 签收配送
   */
  static async signDelivery(deliveryId: string, signData?: {
    signPerson?: string;
    signNote?: string;
  }) {
    try {
      const updateData = {
        status: 1,
        signTime: new Date(),
        ...signData
      };
      
      await dataAPI.save(this.CLASS_NAME, {
        objectId: deliveryId,
        ...updateData
      });
      
      return { success: true };
    } catch (error) {
      console.error('签收配送失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 拒签配送
   */
  static async rejectDelivery(deliveryId: string, rejectData: {
    rejectReason: string;
    rejectNote?: string;
  }) {
    try {
      const updateData = {
        status: 2,
        rejectTime: new Date(),
        rejectReason: rejectData.rejectReason,
        rejectNote: rejectData.rejectNote
      };
      
      await dataAPI.save(this.CLASS_NAME, {
        objectId: deliveryId,
        ...updateData
      });
      
      return { success: true };
    } catch (error) {
      console.error('拒签配送失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 创建配送记录
   */
  static async createDelivery(deliveryData: DeliveryData) {
    try {
      const data = await dataAPI.save(this.CLASS_NAME, {
        ...deliveryData,
        status: 0,
        deliveryTime: new Date()
      });
      
      return { success: true, data };
    } catch (error) {
      console.error('创建配送记录失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 更新配送信息
   */
  static async updateDelivery(deliveryId: string, updateData: Partial<DeliveryData>) {
    try {
      await dataAPI.save(this.CLASS_NAME, {
        objectId: deliveryId,
        ...updateData
      });
      
      return { success: true };
    } catch (error) {
      console.error('更新配送信息失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 删除配送记录
   */
  static async deleteDelivery(deliveryId: string) {
    try {
      await dataAPI.delete(this.CLASS_NAME, deliveryId);
      return { success: true };
    } catch (error) {
      console.error('删除配送记录失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 格式化配送数据
   */
  private static formatDeliveryData(item: any): DeliveryData {
    return {
      objectId: item.objectId,
      cargoNo: item.cargoNo || '',
      orderNo: item.orderNo || '',
      receiverName: item.receiverName || '',
      receiverPhone: item.receiverPhone || '',
      receiverAddress: item.receiverAddress || '',
      senderName: item.senderName || '',
      senderPhone: item.senderPhone || '',
      senderAddress: item.senderAddress || '',
      cargoType: item.cargoType || '',
      totalQuantity: item.totalQuantity || 0,
      totalVolume: item.totalVolume || 0,
      totalWeight: item.totalWeight || 0,
      paymentMethod: item.paymentMethod || 1,
      declaredValue: item.declaredValue || 0,
      insuranceFee: item.insuranceFee || 0,
      deliveryFee: item.deliveryFee || 0,
      unloadingFee: item.unloadingFee || 0,
      collectOnDelivery: item.collectOnDelivery || 0,
      status: item.status || 0,
      signTime: item.signTime ? new Date(item.signTime) : undefined,
      rejectTime: item.rejectTime ? new Date(item.rejectTime) : undefined,
      rejectReason: item.rejectReason || '',
      deliveryTime: item.deliveryTime ? new Date(item.deliveryTime) : undefined,
      driverId: item.driverId || '',
      driverName: item.driverName || '',
      driverPhone: item.driverPhone || '',
      vehiclePlate: item.vehiclePlate || ''
    };
  }

  /**
   * 获取配送状态文本
   */
  static getStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '待签收',
      1: '已签收',
      2: '已拒签',
      3: '异常'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取付款方式文本
   */
  static getPaymentMethodText(method: number): string {
    const methodMap: { [key: number]: string } = {
      1: '预付',
      2: '到付',
      3: '月结'
    };
    return methodMap[method] || '未知';
  }

  /**
   * 获取拒签原因选项
   */
  static getRejectReasons(): Array<{ value: string; label: string }> {
    return [
      { value: 'address_not_found', label: '收货地址找不到' },
      { value: 'receiver_not_available', label: '收货人不在' },
      { value: 'cargo_damaged', label: '货物破损' },
      { value: 'refuse_to_pay', label: '拒绝付款' },
      { value: 'wrong_cargo', label: '货物错误' },
      { value: 'other', label: '其他原因' }
    ];
  }
}